# MakeBy: LiuBoyuan
import os

from fastapi import APIRouter, UploadFile
from fastapi.params import Depends, Body, File, Form
from starlette.responses import Response

from Config import Config
from Schema import WithDataUserSchema, Return
from Schema.UserSchema import UserFormSchema, tokenMixin
from Service.UserService import UserServeiceInstance
from Sissson import get_sission

user = APIRouter()


@user.post("/reg")
def reg(formSchema: UserFormSchema = Body(...), sisson=Depends(get_sission)):
    try:
        ret = UserServeiceInstance.Reg(formSchema, sisson)
        return "okay"
    except:
        return "error"


@user.post("/vtoken", response_model=Return.Boolean)
def vtoken(tokenmixin: tokenMixin = Body(...), sisson=Depends(get_sission)):
    return Return.Boolean(data=UserServeiceInstance.validateToken(tokenmixin, sisson))


@user.post("/login", response_model=WithDataUserSchema)
def login(formSchema: UserFormSchema = Body(...), sisson=Depends(get_sission)):
    ret = UserServeiceInstance.Login(formSchema, sisson)
    if isinstance(ret[0], bool):
        print(ret)
        userModel = ret[2] if ret[0] else None

        return WithDataUserSchema(
            data={
                "ret": ret[0],
                "type": "login",
                "token": ret[1]
            },
            user=userModel
        )
    else:
        return WithDataUserSchema(data={
            "type": "reg"
        })

@user.post("/top_set")
async def top_set(token: str = Body(...), offset : int=Body(...), sisson=Depends(get_sission)):
    """
    设置偏移量
    """
    await UserServeiceInstance.topoffset(token, sisson, offset)
    return "ok"

@user.post("/get_top_set")
def vtoken(tokenmixin: tokenMixin = Body(...), sisson=Depends(get_sission)):
    return UserServeiceInstance.get_topoffset(tokenmixin.token, sisson)

@user.post("/upload_top")
async def upload_image(token: str = Form(...), image: UploadFile = File(...), sisson=Depends(get_sission)):
    """上传图片"""
    await UserServeiceInstance.uploadTopImage(token, sisson, image)
    UserServeiceInstance.topoffset(token, sisson, 0) # 需要额外重置偏移量
    return "ok"

@user.get("/show_topimage")
async def show_image(token: str, sisson=Depends(get_sission), response: Response = None):
    """展示图片"""
    filename = await UserServeiceInstance.TopImage(token, sisson)
    with open(
            os.path.join(Config.File.top_path, filename),
            "rb"
    ) as f:
        read = f.read()
        response.headers["Content-Type"] = f"image/{filename.split('.')[-1]}"
        return Response(read)

# region 头像处理
@user.post("/upload_image")
async def upload_image(token: str = Form(...), image: UploadFile = File(...), sisson=Depends(get_sission)):
    await UserServeiceInstance.uploadHeaderImage(token, sisson, image)
    return "ok"


@user.get("/show_image")
async def show_image(token: str, sisson=Depends(get_sission), response: Response = None):
    filename = await UserServeiceInstance.HeadImage(token, sisson)

    with open(
            os.path.join(Config.File.head_path, filename),
            "rb"
    ) as f:
        read = f.read()
        response.headers["Content-Type"] = f"image/{filename.split('.')[-1]}"
        return Response(read)
# endregion

